import Vue from "vue"
import axios from "axios"

const instance = axios.create({
  timeout: 60000,
});


// 请求拦截
instance.interceptors.request.use(config => {
  // if(["//upload.yl1001.com/upload/files/save","//upload.yl1001.com/upload/images/save"].includes(config.url)) {
  //   // config.headers['Authorization'] = '';
  // }
  return config;
}, err => {
  return Promise.reject(err);
})

//  响应拦截
instance.interceptors.response.use((res) => {
  return Promise.resolve(res.data);
}, (err) => {
  return Promise.reject(err)
})

let request = {
  get: function (url, params = {}) {
    return new Promise((resolve, reject) => {
      instance({
        method: 'get',
        url,
        params,
        transformRequest: function(data) {
          if (Object.prototype.toString.call(data) != '[object FormData]') {
            let src = ''
            for (let item in data) {
              src += encodeURIComponent(item) + '=' + encodeURIComponent(data[item] === null ? '' : data[item]) + '&'
            }
            return src;
          } else {
            return data;
          }
        }
      }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      instance({
        method: 'post',
        url,
        data,
        transformRequest: function(data) {
          if (Object.prototype.toString.call(data) != '[object FormData]') {
            let src = ''
            for (let item in data) {
              src += encodeURIComponent(item) + '=' + encodeURIComponent(data[item] === null ? '' : data[item]) + '&'
            }
            return src;
          } else {
            return data;
          }
        }
      }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default request